<template>
  <div>
    <el-drawer :title="props.mode === 'add' ? '添加' : '编辑'" v-model="visible" :size="1000">
      <template #header>
        <div class="flex items-center title">
          <div class="w-[5px] h-[5px] rounded-[50%] bg-[#3721FF] mr-[10px] circle"></div>
          <div class="tits">{{ props.mode === 'add' ? '添加' : '编辑' }}</div>
        </div>
      </template>
      <div class="w-full h-[1px] bg-[#EFEFEF] line"></div>
      <div class="pt-[30px]">
        <div class="bg-[#FAFAFA] px-[24px] py-[22px] rounded-[4px] formbox">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            require-asterisk-position="right"
            label-width="120"
            :validate-on-rule-change="false"
          >
            <el-row :gutter="20" style="margin-top: 10px">
              <el-col :span="12">
                <el-form-item prop="deptId">
                  <template #label>
                    <div class="flex text-[#101010] items-center"> 部门 </div>
                  </template>
                  <el-tree-select
                    v-model="form.deptId"
                    :data="depatList"
                    :render-after-expand="false"
                    check-strictly
                    @change="handleChangeDept"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="createName">
                  <template #label>
                    <div class="flex text-[#101010] items-center"> 人员 </div>
                  </template>
                  <el-select v-model="form.createName" placeholder="请选择">
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="(item, index) in createNameList"
                      :key="index"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 10px">
              <el-col :span="12">
                <el-form-item prop="advertiserId">
                  <template #label>
                    <div class="flex text-[#101010] items-center"> 广告账户ID </div>
                  </template>
                  <el-input v-model="form.advertiserId" placeholder="请输入广告账户ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="advertiserName">
                  <template #label>
                    <div class="flex text-[#101010] items-center"> 广告账户名称 </div>
                  </template>
                  <el-input v-model="form.advertiserName" placeholder="请输入广告账户名称" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 10px">
              <el-col :span="12">
                <el-form-item>
                  <template #label>
                    <div class="flex text-[#101010] items-center"> 代理商 </div>
                  </template>
                  <el-input v-model="form.agent" placeholder="请输入广告账户ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="appId">
                  <template #label>
                    <div class="flex text-[#101010] items-center"> appId </div>
                  </template>
                  <el-select v-model="form.appId" placeholder="请选择">
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="(item, index) in props.appList"
                      :key="index"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 10px">
              <el-col :span="12">
                <el-form-item prop="status">
                  <template #label>
                    <div class="flex text-[#101010] items-center"> 是否启用 </div>
                  </template>
                  <el-switch
                    v-model="form.status"
                    style="--el-switch-on-color: #3721ff; --el-switch-off-color: #ccc"
                    :active-value="0"
                    :inactive-value="1"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-end">
          <el-button
            @click="hide"
            style="border-radius: 6px !important; width: 109px"
            :loading="buttonLoading"
            >取消</el-button
          >
          <el-button
            type="primary"
            color="#3721FF"
            @click="onSubmit"
            style="border-radius: 6px !important; width: 109px"
            :loading="buttonLoading"
            >确定</el-button
          >
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { AdvertiserApi, AdvertiserVO } from '@/api/ad/advertiser'

import { FormInstance } from 'element-plus'
import { getUserPage } from '@/api/system/user'
import { getUserPageNew } from '@/api/member/user'

const emit = defineEmits(['refresh'])

const props = defineProps({
  curAdvertiser: {
    type: Object as PropType<AdvertiserVO>,
    default: () => {}
  },
  mode: {
    type: String as PropType<'add' | 'edit'>,
    default: 'add'
  },
  depatList: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  appList: {
    type: Array as PropType<any[]>,
    default: () => []
  }
})

const buttonLoading = ref(false)

const formRef = ref<FormInstance | null>(null)

const initFormValue: AdvertiserVO = {
  deptId: null,
  createName: '',
  advertiserId: null,
  advertiserName: null,
  agent: undefined,
  appId: null,
  status: 0
}

const form = ref({
  ...initFormValue
})

watch(
  () => [props.mode, props.curAdvertiser],
  () => {
    if (props.mode === 'edit') {
      form.value = { ...props.curAdvertiser }
    } else {
      form.value = { ...initFormValue }
      formRef.value?.resetFields()
    }
    if (props.curAdvertiser) {
      form.value = { ...props.curAdvertiser }
    }
    console.log(form.value, 'form.value')
  },
  {
    immediate: true,
    deep: true
  }
)

const rules = {
  deptId: [{ required: true, message: '请选择部门', trigger: ['change'] }],
  createName: [{ required: true, message: '请选择创建人', trigger: ['change'] }],
  advertiserId: [{ required: true, message: '请输入广告账户ID', trigger: ['blur'] }],
  advertiserName: [{ required: true, message: '请输入广告账户名称', trigger: ['blur'] }],
  appId: [{ required: true, message: '请选择appID', trigger: ['change'] }]
}

type FormType = {
  fieldName: string
  variableName: string
  type: 'system' | 'custom'
}

const list = ref<FormType[]>([])

const createNameList = ref<any[]>([])

const isQueryed = ref(false)

const visible = ref(false)

watch(
  () => form.value.deptId,
  () => {
    getCreateNameList()
  }
)

const handleChangeDept = () => {
  form.value.createName = ''
}

//查询部门人员
const getCreateNameList = async () => {
  const res = await getUserPageNew({ pageNo: 1, pageSize: 99, deptId: form.value.deptId })
  createNameList.value = res.map((item) => {
    return {
      label: item.nickname,
      value: item.nickname
    }
  })
}

/**
 * 提交
 */
const onSubmit = async () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true
      try {
        if (props.mode === 'edit') {
          await AdvertiserApi.updateAdvertiser(form.value)
        } else {
          await AdvertiserApi.createAdvertiser(form.value)
        }
        hide()
        emit('refresh')
      } finally {
        buttonLoading.value = false
      }
    }
  })
}

const handleCustomField = () => {
  list.value.push({
    fieldName: '',
    variableName: '-',
    type: 'custom'
  })
}

const delRow = (row: FormType) => {
  list.value = list.value.filter((item) => item !== row)
}

const show = () => {
  visible.value = true
}

const hide = () => {
  visible.value = false
}

defineExpose({
  show,
  hide
})
</script>

<style lang="scss" scoped>
:deep(.el-drawer__header) {
  margin-bottom: 0px;
}
:deep(.el-button) {
  height: 39px !important;
  border-radius: 6px !important;
}
</style>
